<?php

namespace app\site\service\auth;
use app\admin\service\site\SiteUserRuleService;
use app\common\exception\MiException;
use app\model\site\SiteUserGroupAccess;
use app\model\site\SiteUserRule;
use app\site\service\CurdService;
use app\admin\validate\auth\AdminValidate;
use app\extend\MiAuth;
use app\model\auth\Admin;
use app\model\auth\AdminGroup;
use app\model\auth\AdminGroupAccess;
use app\model\auth\AdminRule;
use app\model\site\SiteUser;
use app\site\service\SiteBaseService;
use app\site\service\traits\InstanceTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Config;
use think\Model;
use function config;
use function request;
use function validate;

class SiteUserService extends SiteBaseService
{

    use InstanceTrait;

    function initialize()
    {
        $this->model = new SiteUser();
    }

    function formatData(array $data): array
    {
        return $data;
    }

    public function query(): Query
    {
        return $this->setWith(['groups'])->makeQuery()->withoutField("password")->filter(function ($v) {
            $v->groupTitle = getRelValue($v->groups[0]??null, 'title');
            $v->group_id = getRelValue($v->groups[0]??null,'id');
            $v->loginTime = date('Y-m-d H:i:s', $v->login_time);
        });
    }

    /**
     * 保存用户信息
     * @param $post
     * @param string $type
     * @return void
     * @throws MiException
     */
    public function saveInfo($post, string $type){
        if (!in_array($type, ['add', 'edit'])){
            throw new MiException('type值错误');
        }
        $id = $post['id'] ?? '';

        // 验证表单数据
        validate('')->scene($type)->check($post);

        $group_id = $post['group_id'];
        unset($post['group_id']);
        $password = $post['password']??'';
        if ($password){ // 设置了新密码
            $post['password'] = md5($password);
        }else{
            unset($post['password']);
        }
        $curdSer = new CurdService(new SiteUser());
        if ($type == 'add'){
            $admin = $curdSer->create($post);
        }else{
            $admin = $curdSer->update($post, ['id' => $id]);
        }
        // 删除旧的角色关联
        SiteUserGroupAccess::where('uid', $admin->id)->delete();
        // 添加新的角色关联
        SiteUserGroupAccess::create([
            'uid' => $admin->id,
            'group_id' => $group_id
        ]);
    }



}
